<template>
  <div class="app-container">
    <t-form
      :data="queryParams"
      ref="queryRef"
      layout="inline"
      v-show="showSearch"
      class="mb20"
    >
      <t-form-item label="菜单名称" name="menuName">
        <t-input
          v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </t-form-item>
      <t-form-item label="状态" name="status">
        <t-select
          v-model="queryParams.status"
          placeholder="菜单状态"
          clearable
          style="width: 200px"
        >
          <t-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </t-select>
      </t-form-item>
      <t-form-item>
        <t-space>
          <t-button theme="primary" @click="handleQuery">
            搜索
            <template #icon>
              <t-icon name="search" />
            </template>
          </t-button>
          <t-button theme="default" @click="resetQuery">
            重置
            <template #icon>
              <t-icon name="refresh" />
            </template>
          </t-button>
        </t-space>
      </t-form-item>
    </t-form>

    <t-row :gutter="10" class="mb8">
      <t-col :span="1.5">
        <t-button
          theme="primary"
          @click="handleAdd"
          v-hasPermi="['system:menu:add']"
          >新增
          <template #icon>
            <t-icon name="add" />
          </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button theme="default" @click="toggleExpandAll"
          >展开/折叠
          <template #icon>
            <t-icon name="unfold-less" />
          </template>
        </t-button>
      </t-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </t-row>

    <t-enhanced-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menuList"
      row-key="menuId"
      :columns="columns"
      :tree="{ defaultExpandAll: isExpandAll }"
    >
      <template #icon="scope">
        <svg-icon :icon-class="scope.row.icon" />
      </template>
      <template #status="scope">
        <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
      </template>
      <template #createTime="scope">
        <span>{{ parseTime(scope.row.createTime) }}</span>
      </template>
      <template #action="scope">
        <t-button
          variant="text"
          theme="primary"
          @click="handleUpdate(scope.row)"
          v-hasPermi="['system:menu:edit']"
          >修改

          <template #icon>
            <t-icon name="edit" />
          </template>
        </t-button>
        <t-button
          variant="text"
          theme="primary"
          @click="handleAdd(scope.row)"
          v-hasPermi="['system:menu:add']"
          >新增
          <template #icon>
            <t-icon name="add" />
          </template>
        </t-button>
        <t-button
          variant="text"
          theme="primary"
          @click="handleDelete(scope.row)"
          v-hasPermi="['system:menu:remove']"
          >删除
          <template #icon>
            <t-icon name="delete" />
          </template>
        </t-button>
      </template>
    </t-enhanced-table>

    <!-- 添加或修改菜单对话框 -->
    <t-dialog :title="title" v-model:visible="open" width="680px" attach="body">
      <t-form ref="menuRef" :data="form" :rules="rules" label-width="100px">
        <t-row>
          <t-col :span="12" class="mb8">
            <t-form-item label="上级菜单" name="parentId">
              <t-tree-select
                v-model="form.parentId"
                :data="menuOptions"
                :tree-props="{
                  keys: {
                    value: 'menuId',
                    label: 'menuName',
                    children: 'children',
                  },
                }"
                placeholder="选择上级菜单"
              />
            </t-form-item>
          </t-col>
          <t-col :span="12" class="mb8">
            <t-form-item label="菜单类型" name="menuType">
              <t-radio-group v-model="form.menuType">
                <t-radio value="M" label="目录"></t-radio>
                <t-radio value="C" label="菜单"></t-radio>
                <t-radio value="F" label="按钮"></t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
          <t-col :span="12" class="mb8" v-if="form.menuType != 'F'">
            <t-form-item label="菜单图标" name="icon">
              <t-popup
                placement="bottom"
                v-model:visible="showChooseIcon"
                trigger="click"
                @show="showSelectIcon"
                showArrow
              >
                <template #content>
                  <div style="width: 400px">
                    <icon-select ref="iconSelectRef" @selected="selected" />
                  </div>
                </template>
                <t-input
                  v-model="form.icon"
                  placeholder="点击选择图标"
                  @blur="showSelectIcon"
                  v-clickOutside="hideSelectIcon"
                  readonly
                >
                  <template #prefixIcon>
                    <svg-icon
                      v-if="form.icon"
                      :icon-class="form.icon"
                      class="el-input__icon"
                      style="height: 32px; width: 16px"
                    />
                    <t-icon
                      v-else
                      style="height: 32px; width: 16px"
                      name="search"
                    >
                    </t-icon>
                  </template>
                </t-input>
              </t-popup>
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8">
            <t-form-item label="菜单名称" name="menuName">
              <t-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8">
            <t-form-item label="显示排序" name="orderNum">
              <t-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType != 'F'">
            <t-form-item>
              <template #label>
                <span>
                  <t-tooltip
                    content="选择是外链则路由地址需要以`http(s)://`开头"
                    placement="top"
                  >
                    <t-icon name="help-circle-filled" /> </t-tooltip
                  >是否外链
                </span>
              </template>
              <t-radio-group v-model="form.isFrame">
                <t-radio value="0" label="是"></t-radio>
                <t-radio value="1" label="否"></t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType != 'F'">
            <t-form-item name="path">
              <template #label>
                <span>
                  <t-tooltip
                    content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                    placement="top"
                  >
                    <t-icon name="help-circle-filled"></t-icon>
                  </t-tooltip>
                  路由地址
                </span>
              </template>
              <t-input v-model="form.path" placeholder="请输入路由地址" />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType == 'C'">
            <t-form-item name="component">
              <template #label>
                <span>
                  <t-tooltip
                    content="访问的组件路径，如：`system/user/index`，默认在`views`目录下"
                    placement="top"
                  >
                    <t-icon name="help-circle-filled" />
                  </t-tooltip>
                  组件路径
                </span>
              </template>
              <t-input v-model="form.component" placeholder="请输入组件路径" />
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType != 'M'">
            <t-form-item>
              <t-input
                v-model="form.perms"
                placeholder="请输入权限标识"
                :maxlength="100"
              />
              <template #label>
                <span>
                  <t-tooltip
                    content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                    placement="top"
                  >
                    <t-icon name="help-circle-filled" />
                  </t-tooltip>
                  权限字符
                </span>
              </template>
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType == 'C'">
            <t-form-item>
              <t-input
                v-model="form.query"
                placeholder="请输入路由参数"
                :maxlength="255"
              />
              <template #label>
                <span>
                  <t-tooltip
                    content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'
                    placement="top"
                  >
                    <t-icon name="help-circle-filled" />
                  </t-tooltip>
                  路由参数
                </span>
              </template>
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType == 'C'">
            <t-form-item>
              <template #label>
                <span>
                  <t-tooltip
                    content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                    placement="top"
                  >
                    <t-icon name="help-circle-filled" />
                  </t-tooltip>
                  是否缓存
                </span>
              </template>
              <t-radio-group v-model="form.isCache">
                <t-radio value="0">缓存</t-radio>
                <t-radio value="1">不缓存</t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType != 'F'">
            <t-form-item>
              <template #label>
                <span>
                  <t-tooltip
                    content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                    placement="top"
                  >
                    <t-icon name="help-circle-filled" />
                  </t-tooltip>
                  显示状态
                </span>
              </template>
              <t-radio-group v-model="form.visible">
                <t-radio
                  v-for="dict in sys_show_hide"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
          <t-col :span="6" class="mb8" v-if="form.menuType != 'F'">
            <t-form-item>
              <template #label>
                <span>
                  <t-tooltip
                    content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                    placement="top"
                  >
                    <t-icon name="help-circle-filled" />
                  </t-tooltip>
                  菜单状态
                </span>
              </template>
              <t-radio-group v-model="form.status">
                <t-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
      <template #footer>
        <div class="dialog-footer">
          <t-button theme="primary" @click="submitForm">确 定</t-button>
          <t-button theme="default" @click="cancel">取 消</t-button>
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script setup name="Menu">
import {
  addMenu,
  delMenu,
  getMenu,
  listMenu,
  updateMenu,
} from "@/api/system/menu";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";

const { proxy } = getCurrentInstance();
const { sys_show_hide, sys_normal_disable } = proxy.useDict(
  "sys_show_hide",
  "sys_normal_disable"
);

const menuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);
const menuRef = ref(null);

const columns = ref([
  { colKey: "menuName", label: "菜单名称", width: 160, ellipsis: true },
  { colKey: "icon", label: "图标", align: "center", width: 100 },
  { colKey: "orderNum", label: "排序", width: 60 },
  { colKey: "perms", label: "权限标识", ellipsis: true },
  { colKey: "component", label: "组件路径", ellipsis: true },
  { colKey: "status", label: "状态", width: 80 },
  { colKey: "createTime", label: "创建时间", width: 180 },
  { colKey: "action", label: "操作", width: 300, fixed: "right" },
]);

const data = reactive({
  form: {},
  queryParams: {
    menuName: undefined,
    visible: undefined,
  },
  rules: {
    parentId: [
      { required: true, message: "上级菜单不能为空", trigger: "blur" },
    ],
    menuName: [
      { required: true, message: "菜单名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "菜单顺序不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询菜单列表 */
function getList() {
  loading.value = true;
  listMenu(queryParams.value).then((response) => {
    menuList.value = proxy.handleTree(response.data, "menuId");
    loading.value = false;
  });
}
/** 查询菜单下拉树结构 */
function getTreeselect() {
  listMenu().then((response) => {
    const menu = { menuId: 0, menuName: "主类目", children: [] };
    menu.children = proxy.handleTree(response.data, "menuId");
    menuOptions.value = [menu];
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    menuId: undefined,
    parentId: undefined,
    menuName: undefined,
    icon: undefined,
    menuType: "M",
    orderNum: undefined,
    isFrame: "1",
    isCache: "0",
    visible: "0",
    status: "0",
  };
  proxy.resetForm("menuRef");
}
/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
  showChooseIcon.value = true;
}
/** 选择图标 */
function selected(name) {
  form.value.icon = name;
  showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event) {
  var elem =
    event.relatedTarget ||
    event.srcElement ||
    event.target ||
    event.currentTarget;
  if (elem && elem.className !== "t-input__inner") {
    showChooseIcon.value = false;
  }
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  // if (row != null && row.menuId) {
  //   form.value.parentId = row.menuId;
  // } else {
  //   form.value.parentId = 0;
  // }
  open.value = true;
  title.value = "添加菜单";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getTreeselect();
  getMenu(row.menuId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改菜单";
  });
}
/** 提交按钮 */
function submitForm() {
  menuRef.value.validate().then((valid) => {
    if (valid) {
      if (form.value.menuId != undefined) {
        updateMenu(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMenu(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.menuName + '"的数据项?')
    .then(function () {
      return delMenu(row.menuId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
